package com.fingard.dsp.bank.directbank.icbc02;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.ReqAuthForRecDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryAuthForRecDetail;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryRecAuthInfoDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ICBC02AuthorizeForRec extends ICBC02Base implements IAuthorizeForRec {
    @Override
    public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) {
        RetAtsAuthForRec tmpRetAts = new RetAtsAuthForRec(p_req.reqHeader);
        try {
            bnkPackageID = p_req.reqSeqID;
            bnkfSeqno = p_req.reqSeqID;
            bnkTransCode = "ENDIIMPT";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("TotalNum", String.valueOf(p_req.detailCount));//总笔数
            xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(new Date()));//签名时间
            xmlWriter.writeElementString("ContractNo", getBankConfig().getValueAsString("contractNo"));//协议编号
            String payType = p_req.payType;
            if (StringHelper.isNullOrEmpty(payType)) {
                payType = getBankConfig().getValueAsString("payType");
            }
            xmlWriter.writeElementString("PayType", payType);//缴费种类
            xmlWriter.writeElementString("AcctName", p_req.ownActName);//企业名称
            xmlWriter.writeElementString("AcctNo", p_req.ownAct);//企业账号
            xmlWriter.writeElementString("ReqReserved1", p_req.reqReserved1);//请求备用字段1
            xmlWriter.writeElementString("ReqReserved2", p_req.reqReserved2);//请求备用字段2
            int index = 0;
            while (p_req.readRecord()) {
                ReqAuthForRecDetail tmpDetail = p_req.readedDetail;
                index++;
                xmlWriter.writeStartElement("rd");
                xmlWriter.writeElementString("iSeqno", index + "");//指令顺序号
                xmlWriter.writeElementString("PayNo", tmpDetail.authCode);//缴费编号
                xmlWriter.writeElementString("PayAcctName", tmpDetail.oppActName);//缴费客户姓名
                xmlWriter.writeElementString("PayAccNo", tmpDetail.oppAct);//缴费客户账号
                xmlWriter.writeElementString("CertType", tmpDetail.certType);//证件类型
                xmlWriter.writeElementString("CertNo", tmpDetail.certNum);//证件号码
                String bkDeadLine = tmpDetail.deadLine;
                if (StringHelper.hasAnyChar(bkDeadLine)) {
                    bkDeadLine = bkDeadLine.replace("-", "");
                }
                xmlWriter.writeElementString("DeadLine", bkDeadLine);//过期日期
                xmlWriter.writeElementString("ReqReserved3", tmpDetail.reqReserved3);//请求备用字段3
                xmlWriter.writeElementString("ReqReserved4", tmpDetail.reqReserved4);//请求备用字段4
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), true);
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                if (tmpStrRet[1].startsWith("errorCode＝")) {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpStrRet[1].replace("errorCode＝", "");
                    return tmpRetAts;
                }
                if (tmpStrRet[1].contains("reqData=")) {
                    tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("reqData=") + 8, tmpStrRet[1].length());
                }
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetAts.respCode = "0";
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    if ("0".equals(tmpRetCode)) {
                        tmpRetAts.retCode = "2";
                    } else {
                        tmpRetAts.retCode = "1";
                    }
                    tmpRetAts.reqSeqID = tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno");
                    tmpRetAts.serialNo = tmpBkReader.getFirstText("/CMS/eb/pub/SerialNo");
                    tmpRetAts.retMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    @Override
    public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) {
        RetAtsQryAuthForRec tmpRetAts = new RetAtsQryAuthForRec(p_req.reqHeader);
        tmpRetAts.writeStart();
        try {
            String tmpRespCode = "";
            String tmpRespInfo = "";
            int qryCount = 0;
            String nextTag = "";
            bnkTransCode = "QENDIIMPT";
            while (tmpRespCode.length() == 0) {
                qryCount++;
                bnkPackageID = p_req.reqHeader.transSeqID + String.valueOf(qryCount);
                if (bnkPackageID.length() > 35) {
                    bnkPackageID = bnkPackageID.substring(bnkPackageID.length() - 35, bnkPackageID.length());
                }
                bnkfSeqno = bnkPackageID;
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入ICBC02通用的头部节点，<in>之后
                //writeCommonHeader(xmlWriter);
                if (StringHelper.isNullOrEmpty(bnkTransCode)) {
                    throw new Exception("未赋值TransCode");
                }
                if (StringHelper.isNullOrEmpty(bnkPackageID)) {
                    throw new Exception("未赋值PackageID");
                }
                if (StringHelper.isNullOrEmpty(bnkfSeqno)) {
                    throw new Exception("未赋值fSeqno");
                }
                xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"GBK\"?>");
                xmlWriter.writeStartElement("CMS");
                xmlWriter.writeStartElement("eb");
                xmlWriter.writeStartElement("pub");
                xmlWriter.writeElementString("TransCode", bnkTransCode);
                xmlWriter.writeElementString("CIS", bankFront.org);
                xmlWriter.writeElementString("BankCode", bnkBankCode);
                xmlWriter.writeElementString("ID", bankFront.keyID);
                Date tmpDateNow = new Date();
                xmlWriter.writeElementString("TranDate", Format.Date8Format.format(tmpDateNow));
                xmlWriter.writeElementString("TranTime", Format.Time9Format.format(tmpDateNow));
                xmlWriter.writeElementString("fSeqno", bnkfSeqno);
                xmlWriter.writeEndElement();

                xmlWriter.writeStartElement("out");
                xmlWriter.writeElementString("StartDate", "", true);//查询起始日期
                xmlWriter.writeElementString("EndDate", "", true);//查询截至日期
                xmlWriter.writeElementString("QryfSeqno", p_req.reqSeqID);//待查指令包序号
                xmlWriter.writeElementString("NextTag", nextTag, true);//查询下页标识
                xmlWriter.writeElementString("ReqReserved1", "", true);//提交备用字段1
                xmlWriter.writeElementString("ReqReserved2", "", true);//提交备用字段2

                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                        if (isActiveRetCode(tmpRetCode)) {
                            nextTag = tmpBkReader.getFirstText("/CMS/eb/out/NextTag");
                            String tmpTotalNum = tmpBkReader.getFirstText("/CMS/eb/out/TotalNumber");
                            if (StringHelper.isNullOrEmpty(tmpTotalNum)) {
                                tmpRespCode = "-1";
                                tmpRespInfo = "银行返回的交易条数为空";
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
                while (tmpBkReader.read("/CMS/eb/out/rd")) {
                    RetAtsQryAuthForRecDetail tmpDetail = new RetAtsQryAuthForRecDetail();
                    XElement tmpRd = tmpBkReader.readedXElement;
                    tmpDetail.iSeqno = tmpRd.getSingleText("PayNo");
                    tmpDetail.payInfo = tmpRd.getSingleText("iRetMsg");
                    tmpDetail.contractNo = tmpRd.getSingleText("ContractNo");
                    tmpDetail.authCode = tmpRd.getSingleText("PayNo");
                    tmpDetail.oppAct = tmpRd.getSingleText("PayAcctNo");
                    tmpDetail.oppActName = tmpRd.getSingleText("PayAcctName");
                    tmpDetail.deadLine = tmpRd.getSingleText("DeadLine");
                    tmpDetail.payType = tmpRd.getSingleText("PayType");
                    String tmpResult = tmpRd.getSingleText("Result");
                    if ("6".equals(tmpResult) || "8".equals(tmpResult)) {
                        tmpDetail.transState = "3";
                    } else if ("7".equals(tmpResult)) {
                        tmpDetail.transState = "2";
                    } else {
                        tmpDetail.transState = "4";
                    }
                    tmpDetail.payCode = tmpRd.getSingleText("iRetCode");
                    tmpRetAts.writeRetDetail(tmpDetail);
                }

                if (StringHelper.isNullOrEmpty(nextTag)) {
                    break;
                }
            }

            tmpRetAts.respCode = tmpRespCode;
            tmpRetAts.respInfo = tmpRespInfo;
            tmpRetAts.reqSeqID = p_req.reqSeqID;
            if ("0".equals(tmpRespCode) && tmpRetAts.getWriteRdCount() <= 0) {
                tmpRetAts.transState = "4";
            }

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if (tmpRetAts.getWriteRdCount() <= 0) {
            tmpRetAts.writeRetHead();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }

    @Override
    public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
        if ("1".equals(p_req.isPrivate)) {
            return d_qry_authInfo_pri(p_req);
        } else {
            return d_qry_authInfo_pub(p_req);
        }

    }

    private RetAtsQryRecAuthInfo d_qry_authInfo_pri(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        try {
            String tmpRespCode = "";
            String tmpRespInfo = "";
            int qryCount = 0;
            String nextTag = "";
            bnkTransCode = "QPERINF";
            tmpRetAts.ownAct = p_req.ownAct;
            while (tmpRespCode.length() == 0) {
                qryCount++;
                bnkPackageID = p_req.reqHeader.transSeqID + String.valueOf(qryCount);
                if (bnkPackageID.length() > 35) {
                    bnkPackageID = bnkPackageID.substring(bnkPackageID.length() - 35, bnkPackageID.length());
                }
                bnkfSeqno = bnkPackageID;
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入ICBC02通用的头部节点，<in>之后
                writeCommonHeader(xmlWriter);
                xmlWriter.writeElementString("BeginDate", p_req.dateFrom);//起始日期
                xmlWriter.writeElementString("EndDate", p_req.dateTo);//终止日期
                xmlWriter.writeElementString("BeginTime", "");//开始时间
                xmlWriter.writeElementString("EndTime", "");//终止时间
                xmlWriter.writeElementString("RecAccNo", p_req.ownAct);//收费企业账号
                xmlWriter.writeElementString("PayAccNo", p_req.oppAct);//付款账号
                xmlWriter.writeElementString("Portno", "");//缴费编号
                xmlWriter.writeElementString("QueryTag", p_req.queryTag);//查询协议类型 0：签订协议  1：撤销协议
                xmlWriter.writeElementString("NextTag", nextTag);//查询下页标识
                xmlWriter.writeElementString("ReqReserved1", "");//提交备用字段1
                xmlWriter.writeElementString("ReqReserved2", "");//提交备用字段2

                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                        if (isActiveRetCode(tmpRetCode)) {
                            nextTag = tmpBkReader.getFirstText("/CMS/eb/out/NextTag");
                            String tmpTotalNum = tmpBkReader.getFirstText("/CMS/eb/out/TotalNum");
                            //tmpRespCode = "0";
                            while (tmpBkReader.read("/CMS/eb/out/rd")) {
                                tmpRetAts.respCode = "0";
                                RetAtsQryRecAuthInfoDetail tmpDetail = new RetAtsQryRecAuthInfoDetail();
                                XElement tmpRd = tmpBkReader.readedXElement;
                                tmpDetail.oppActName = tmpRd.getSingleText("PayAccNameCN");
                                tmpDetail.oppAct = tmpRd.getSingleText("PayAccNo");
                                tmpDetail.queryTag = p_req.queryTag;
                                tmpDetail.authDateFrom = tmpRd.getSingleText("SignDate");
                                tmpDetail.respReserve1 = tmpRd.getSingleText("ContractNo");
                                tmpDetail.respReserve2 = tmpRd.getSingleText("Portno");
                                tmpDetail.respReserve3 = tmpRd.getSingleText("OpType");
                                tmpRetAts.writeRetDetail(tmpDetail);
                            }
                            if (StringHelper.isNullOrEmpty(nextTag)) {
                                tmpRespCode = "0";
                                tmpRespInfo = tmpRetMsg;
                                break;
                            }
                        } else {
                            tmpRespCode = "0";//继续往下走
                            tmpRespInfo = tmpRetMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }

            }
            tmpRetAts.respCode = tmpRespCode;
            tmpRetAts.respInfo = tmpRespInfo;
            tmpRetAts.ownAct = p_req.ownAct;

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }

    private RetAtsQryRecAuthInfo d_qry_authInfo_pub(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        try {
            String tmpRespCode = "";
            String tmpRespInfo = "";
            int qryCount = 0;
            String nextTag = "";
            bnkTransCode = "QENTINF";
            tmpRetAts.ownAct = p_req.ownAct;
            while (tmpRespCode.length() == 0) {
                qryCount++;
                bnkPackageID = p_req.reqHeader.transSeqID + String.valueOf(qryCount);
                if (bnkPackageID.length() > 35) {
                    bnkPackageID = bnkPackageID.substring(bnkPackageID.length() - 35, bnkPackageID.length());
                }
                bnkfSeqno = bnkPackageID;
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入ICBC02通用的头部节点，<in>之后
                writeCommonHeader(xmlWriter);
                xmlWriter.writeElementString("BeginDate", p_req.dateFrom);//起始日期
                xmlWriter.writeElementString("EndDate", p_req.dateTo);//终止日期
                xmlWriter.writeElementString("BeginTime", "");//开始时间
                xmlWriter.writeElementString("EndTime", "");//终止时间
                xmlWriter.writeElementString("RecAccNo", p_req.ownAct);//收费企业账号
                xmlWriter.writeElementString("PayAccNo", p_req.oppAct);//付款账号
                xmlWriter.writeElementString("NextTag", nextTag);//查询下页标识
                xmlWriter.writeElementString("ReqReserved1", "");//提交备用字段1
                xmlWriter.writeElementString("ReqReserved2", "");//提交备用字段2

                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                        String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                        if (isActiveRetCode(tmpRetCode)) {
                            nextTag = tmpBkReader.getFirstText("/CMS/eb/out/NextTag");
                            String tmpTotalNum = tmpBkReader.getFirstText("/CMS/eb/out/TotalNum");
                            //tmpRespCode = "0";
                            while (tmpBkReader.read("/CMS/eb/out/rd")) {
                                tmpRetAts.respCode = "0";
                                RetAtsQryRecAuthInfoDetail tmpDetail = new RetAtsQryRecAuthInfoDetail();
                                XElement tmpRd = tmpBkReader.readedXElement;
                                tmpDetail.oppActName = tmpRd.getSingleText("PayAccNameCN");
                                tmpDetail.oppAct = tmpRd.getSingleText("PayAccNo");
                                tmpDetail.queryTag = p_req.queryTag;
                                tmpDetail.authDateFrom = tmpRd.getSingleText("SignDate");
                                tmpRetAts.writeRetDetail(tmpDetail);
                            }
                            if (StringHelper.isNullOrEmpty(tmpTotalNum) && StringHelper.isNullOrEmpty(nextTag)) {
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
            }
            tmpRetAts.respCode = tmpRespCode;
            tmpRetAts.respInfo = tmpRespInfo;
            tmpRetAts.ownAct = p_req.ownAct;

        } catch (Exception ex) {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }
}
